/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */
#include "virtualpagemanager.h"

#include <machine/pc/memory/memmanager.h>
#include <machine/pc/memory/virtualpagewithoutpae4k.h>
#include <machine/machine.h>
#include <kerneldebugconsole.h>

PLVirtualPageManager::PLVirtualPageManager() {
}

void PLVirtualPageManager::init() {
	// Add more maging methodes and make it bootmanager configuratable for the kernel.
	m_pagingMethode = new PLVirtualPageWithoutPAE4k();
	((PLStaticMemHandler *)PLMachine::instance().kernelMemManger()->memhander())->alignToPage(m_pagingMethode->pageSize());
	m_pagingMethode->init(this);
}

void PLVirtualPageManager::createKernelVirtualAddresses() {
	// Pages that are used from the kernel.
	uint32_t lastMemPos = ((((PLStaticMemHandler *)PLMachine::instance().kernelMemManger()->memhander())->currentMem() + (m_pagingMethode->pageSize() - 1)) / m_pagingMethode->pageSize());
	for(uint32_t i = 0 ; i <= lastMemPos ; i++) {
		mapPage((void*)(i * m_pagingMethode->pageSize()), (void*)(i * m_pagingMethode->pageSize()), PLVirtualPageManager::PageTablePresent | PLVirtualPageManager::PageTableReadWrite);
	}
	PLKernelDebugConsole::instance().printf("\n   Mapped to same address for kernel to address: 0x%x", (lastMemPos * m_pagingMethode->pageSize()));
}

void PLVirtualPageManager::setPageDirectory(uint32_t address) {
	PLKernelDebugConsole::instance().printf("\n   Set page directory to address: 0x%x", address);
	asm volatile("movl %0   , %%eax\n"
					 "movl %%eax, %%cr3\n" :: "m"(address) : "eax");
}

void PLVirtualPageManager::stopPaging() {
	asm volatile("mov %%cr0       , %%eax\n"
					 "and  $0x7fffffff, %%eax\n"
					 "mov %%eax       , %%cr0\n"
					 ::: "ax");
}

void PLVirtualPageManager::flushPageCache() const {
	asm volatile("mov %%cr3, %%eax\n"
					 "mov %%eax, %%cr3\n"
					 ::: "ax");
}
